package cn.tohsaka.factory.dockercraft.Handlers;

import cn.tohsaka.factory.dockercraft.Interfaces.EventBasedWebSocketConnection;
import cn.tohsaka.factory.dockercraft.Interfaces.WebSocketEventBean;
import cn.tohsaka.factory.dockercraft.Libraries.EventHandler;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.webbitserver.WebSocketConnection;
import org.webbitserver.WebSocketHandler;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Xmsoft on 2017/8/20.
 */
public class EventBasedWebSocketHandler implements WebSocketHandler {
    public static List<EventHandler> events=new ArrayList<EventHandler>();
    @Override
    public void onOpen(WebSocketConnection webSocketConnection) throws Throwable {
        EventHandler.emit(events,"open",null,new EventBasedWebSocketConnection(webSocketConnection));
    }

    @Override
    public void onClose(WebSocketConnection webSocketConnection) throws Throwable {
        EventHandler.emit(events,"close",null,new EventBasedWebSocketConnection(webSocketConnection));
    }

    @Override
    public void onMessage(WebSocketConnection webSocketConnection, String s) throws Throwable {
        try {
            WebSocketEventBean web=new Gson().fromJson(s,new TypeToken<WebSocketEventBean>(){}.getType());
            EventHandler.emit(events,web.e,web.data,new EventBasedWebSocketConnection(webSocketConnection));
        }catch (Exception e){
            EventHandler.emit(events,"Exception",e,new EventBasedWebSocketConnection(webSocketConnection));
        }
    }

    @Override
    public void onMessage(WebSocketConnection webSocketConnection, byte[] bytes) throws Throwable {
        onMessage(webSocketConnection,new String(bytes));
    }

    @Override
    public void onPing(WebSocketConnection webSocketConnection, byte[] bytes) throws Throwable {

    }

    @Override
    public void onPong(WebSocketConnection webSocketConnection, byte[] bytes) throws Throwable {

    }
}
